import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';

import Toast from '@vant/weapp/toast/toast';
Page({
  data: {
    defaultData: {
      title: "填写退货信息", // 导航栏标题
      imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },
    imageURL: "https://zntg.swehszn.com/file/WechatIMG637.png",
    fileImageList: [], // log图片的列表
    fileVideoList: [], // 首页图片的列表
    afterSalesProducts: [],
    afterSalesOrder: {},
    submitName: "",
    radioDelivery: '1',
    radio: "2",
    merchantList: [],
    address: "",
    contact: "",
    phone: "",
    totalGoodsCount: 0,
    totalGoodsSubtotal: 0,
    orderId: null,
    products: {},
    serviceType: "换货",
    imgUrl: "",
    videoUrl: "",
    funInfo: "",
    status: null,
    orderNo: "",
    reasonDesc: "",
    id: null,
    payWay: "2",
    isSubscribed: false, // 标志变量，表示是否已订阅
    SUBSCRIBE_TIMEOUT: 10000, // 设置时间间隔（例如：10秒）
  },

  onLoad(options) {
    const status = wx.getStorageSync('status');
    this.setData({
      status
    })
    console.log("status", this.data.status);

    if (status == -1) {
      this.getAfterSalesProducts()
      this.setData({
        orderId: options.orderId,
        orderNo: options.orderNo
      })
    } else {
      this.getAfterSalesOrder()
    }
  },

  onShow() {
    if (this.data.status == -1) {
      this.getDictionary()
      this.orderStatistical()
    }
  },

  // 底部状态
  statusName() {
    const {
      status,
      afterSalesOrder
    } = this.data
    let newsubmitName = ""
    if (status == -1) {
      newsubmitName = "申请"
    } else if (status == 1) {
      newsubmitName = afterSalesOrder.statusName
    } else if (status == 2) {
      newsubmitName = "提交"
    } else if (status == 3) {
      newsubmitName = afterSalesOrder.isPay == 1 ? "支付" : afterSalesOrder.statusName
    } else if (status == 4) {
      newsubmitName = "确认收货"
    } else {
      newsubmitName = "订单已完成"
    }

    console.log("newsubmitName", newsubmitName);

    this.setData({
      submitName: newsubmitName
    })
  },

  //配送方式
  deliveryMethod(event) {
    this.setData({
      radioDelivery: event.detail, // 更新选择状态
    });
  },

  //获取申请售后商品
  getAfterSalesProducts() {
    const afterSalesProducts = wx.getStorageSync('afterSalesProducts');
    console.log("afterSalesProducts", afterSalesProducts);
    const updatedAfterSalesProducts = afterSalesProducts.map(item => ({
      productId: item.id,
      goodsCount: item.goodsCount,
      goodsSubtotal: item.goodsSubtotal
    }));

    this.setData({
      afterSalesProducts,
      products: updatedAfterSalesProducts
    })

    console.log("获取售后商品", this.data.afterSalesProducts);
    console.log("获取接口参数售后商品", this.data.products);


    wx.removeStorageSync('afterSalesProducts');
    if (afterSalesProducts.length > 0) {
      const firstProduct = afterSalesProducts[0];
      if (firstProduct.merchantName == '') {
        firstProduct.merchantName = "中山市鸿世电器经营部";
        // 更新数据
        this.setData({
          afterSalesProducts
        });
      }
    }
    this.statusName()
  },

  //获取售后中商品
  getAfterSalesOrder() {
    const afterSalesOrder = wx.getStorageSync('afterSalesOrder');
    console.log("afterSalesOrder", afterSalesOrder);

    const imgUrls = afterSalesOrder.imgUrl ? afterSalesOrder.imgUrl.split(',').map(url => ({
      url
    })) : [];

    const videoUrls = afterSalesOrder.videoUrl ? afterSalesOrder.videoUrl.split(',').map(url => ({
      url
    })) : [];

    this.setData({
      afterSalesOrder,
      radio: afterSalesOrder.serviceType == "换货" ? "2" : "1",
      reasonDesc: afterSalesOrder.reasonDesc,
      fileImageList: imgUrls,
      fileVideoList: videoUrls,
      merchantName: afterSalesOrder.merchantName,
      contact: afterSalesOrder.consigneeName,
      phone: afterSalesOrder.consigneePhone,
      address: afterSalesOrder.consigneeAdr,
      id: afterSalesOrder.id,
      funInfo: this.data.status == 2 ? '' : afterSalesOrder.orderNo
    });

    console.log("reasonDesc", this.data.reasonDesc);
    console.log("fileImageList", this.data.fileImageList);
    this.orderStatistical();
    this.statusName()
  },


  //商品总数量和商品总价
  orderStatistical() {
    const {
      afterSalesProducts,
      afterSalesOrder,
      status
    } = this.data;
    let totalGoodsCount = 0;
    let totalGoodsSubtotal = 0.0;
    let products = []

    if (status == -1) {
      products = afterSalesProducts
    } else {
      products = afterSalesOrder.products
    }

    // 计算商品总数量和总价格
    products.forEach(product => {
      totalGoodsCount += parseInt(product.goodsCount, 10);
      totalGoodsSubtotal += parseFloat(product.goodsSubtotal);
    });
    this.setData({
      totalGoodsCount,
      totalGoodsSubtotal: totalGoodsSubtotal.toFixed(2)
    });

    console.log("统计后的totalGoodsCount", this.data.totalGoodsCount);
  },


  // 监听输入框的输入事件
  onInputRemark(event) {
    const inputText = event.detail.value;
    this.setData({
      reasonDesc: inputText
    });
    console.log("当前原因说明:", this.data.reasonDesc);
  },

  onChange(event) {
    this.setData({
      radio: event.detail
    });
  },

  // 获取字典，商户退货地址
  async getDictionary() {
    try {
      const res = await request({
        url: indexApi.getSysDicApi("MERCHANT_ADDRESS"),
        data: {}
      });

      this.setData({
        merchantList: res.data
      });
      console.log("获取字典，商户退货地址", this.data.merchantList);
      this.matchMerchantInfo();
    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 匹配售后商品的商户信息
  matchMerchantInfo() {
    const {
      afterSalesProducts,
      merchantList
    } = this.data;

    // if (!afterSalesProducts || !merchantList || afterSalesProducts.length === 0) return;

    // 只查看第一个商品
    const firstProduct = afterSalesProducts[0];
    const merchant = merchantList.find(item => item.name === firstProduct.merchantName);
    console.log("只查看第一个商品的商户", merchant);

    if (merchant && merchant.code) {
      const [address, contact, phone] = merchant.code.split('$');
      console.log(`地址: ${address || ''}, 联系人: ${contact || ''}, 电话: ${phone || ''}`);
      const merchantName = afterSalesProducts[0].merchantName == "" ? "中山市鸿世电器经营部" : afterSalesProducts[0].merchantName

      // 更新数据
      this.setData({
        merchantName,
        address,
        contact,
        phone
      });
    }
  },

  // 上传图片
  afterRead(event) {
    const {
      file
    } = event.detail;
    const type = event.currentTarget.dataset.type;

    if (type === 'Image') {
      if (file.size > 200 * 1024) {
        wx.compressImage({
          src: file.url,
          quality: 80,
          success: (res) => {
            file.url = res.tempFilePath;
            this.uploadFile(file, type);
          },
          fail: () => {
            wx.showToast({
              title: '图片压缩失败',
              icon: 'none'
            });
          }
        });
      } else {
        this.uploadFile(file, type);
      }

    } else if (type === 'Video') {
      if (file.size > 5 * 1024 * 1024) {
        wx.showToast({
          title: '视频超过5MB，无法上传',
          icon: 'none'
        });
      } else {
        this.uploadFile(file, type);
      }
    }
  },


  async uploadFile(file, type) {
    try {
      const uploadTask = wx.uploadFile({
        url: indexApi.upLoadApi(),
        header: {
          "Content-Type": "multipart/form-data"
        },
        filePath: file.url,
        name: 'file',
        formData: {},
        success: (res) => {
          const data = JSON.parse(res.data);
          console.log('Upload success', data);
          file.url = data.data;
          if (type === 'Image') {
            this.setData({
              fileImageList: [...this.data.fileImageList, file]
            });
            console.log("fileImageList", this.data.fileImageList);
          } else if (type === 'Video') {
            this.setData({
              fileVideoList: [...this.data.fileVideoList, file]
            });
            console.log("fileVideoList", this.data.fileListHome);
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        },
      });
    } catch (error) {
      wx.showToast({
        title: '上传失败,请联系管理员',
        icon: 'none'
      });
    }
  },

  // 删除图片回调
  onDelete(event) {
    const type = event.target.dataset.type;
    const {
      index
    } = event.detail;
    if (type === 'Image') {
      fileImageList.splice(index, 1);
      this.setData({
        fileImageList
      });
    } else if (type === 'Video') {
      fileVideoList.splice(index, 1);
      this.setData({
        fileVideoList
      });
    }
  },

  // 提取图片URL和视频
  generateImageUrlString() {
    const imgUrls = this.data.fileImageList.map(file => file.url).join(',');
    const videoUrls = this.data.fileVideoList.map(file => file.url).join(',');
    this.setData({
      imgUrl: imgUrls,
      videoUrl: videoUrls
    });
    console.log("imgUrl:", this.data.imgUrl);
    console.log("videoUrl:", this.data.videoUrl);
  },

  // 物流单号
  funInfoChange(event) {
    const inputText = event.detail;
    this.setData({
      funInfo: inputText
    });
    console.log("当前物流单号:", this.data.funInfo);
  },

  async submit() {

    const {
      status,
    } = this.data
    let reqSearch = {}
    if (status == -1) {

      reqSearch = this.submitApply()
    } else if (status == 2) {
      if (this.data.funInfo == "") {
        Toast('物流单号不能为空');
        console.log("物流单号不能为空");
        return;
      } else {
        reqSearch = {
          id: this.data.id,
          logisticsNo: this.data.funInfo,
          status: Number(status) + 1,
        }
      }
    } else if (status == 3) {
      if (this.data.afterSalesOrder.isPay == 1) {
        try {
          await this.placeOrder();
          reqSearch = {
            id: this.data.id,
            isPay: 0
          };
          this.setData({
            status: 7
          });
        } catch (error) {
          console.error("下单失败:", error);
          wx.showToast({
            title: '下单失败，请重试',
            icon: 'none'
          });
        }
      } else {

        wx.navigateBack()
      }
    } else if (status == 4) {
      reqSearch = {
        id: this.data.id,
        status: Number(status) + 2,
      }
    } else {

      wx.navigateBack()
    }
    console.log("this.data.status", this.data.status);
    if (status == -1 || status == 2 || this.data.status == 7 || status == 4) {
      try {
        const res = await request({
          url: indexApi.saveOrUpdateAfterOrderApi(),
          method: "POST",
          data: reqSearch
        });
        if (status == -1) {
          wx.navigateBack({
            delta: 2
          })
        } else {
          wx.navigateBack({
            delta: 1
          })
        }


      } catch (error) {
        console.error("Error:", error);
      }
    }
  },

  submitApply() {
    this.generateImageUrlString();
    const {
      afterSalesProducts,
      orderId,
      serviceType,
      products,
      imgUrl,
      videoUrl,
      address,
      contact,
      phone,
      orderNo,
      reasonDesc,
      merchantName,
      status,
      funInfo,
      id
    } = this.data;
    const Newstatus = status == -1 ? 1 : Number(status) + 1;
    console.log("Newstatus", Newstatus);

    const reqSearch = {
      orderId: orderId,
      serviceType: serviceType,
      products: products,
      imgUrl: imgUrl,
      videoUrl: videoUrl,
      reasonDesc,
      logisticsNo: funInfo,
      status: Newstatus,
      merchantName,
      consigneeAdr: address,
      consigneeName: contact,
      consigneePhone: phone,
      orderNo,
    };

    return reqSearch;
  },

  //选择付款方式
  paymentChange(event) {
    console.log("付款方式", event.detail);
    this.setData({
      payWay: event.detail
    })
  },


  //支付下单
  async placeOrder() {
    const {
      afterSalesOrder
    } = this.data
    // const reqTemplate = {
    //   orderId: this.data.orderId,
    //   payWay:this.data.payWay
    // }
    // if (this.data.agree == false) {
    //   Toast('请同意协议和政策');
    //   return;
    // }else{
    try {
      const res = await request({
        url: indexApi.payMallOrderApi(),
        method: "POST",
        data: {
          id: afterSalesOrder.id
        }
      });
      console.log("res========", res);
      this.requestPayment(res.data)
      // if (this.data.payWay == 1) {
      //   this.requestPayment(res.data)
      //   console.log("支付结果", res.data);
      // } else {
      //   if (res.success == false) {
      //     Toast('余额不足！');
      //     return;
      //   }
      // else{
      //   this.getpaydOrder()
      // }
      // }

    } catch (error) {
      console.error("Error:", error);
    }
    // } 
  },


  //支付
  requestPayment(data) {
    const that = this;
    return new Promise((resolve, reject) => {
      wx.requestPayment({
        timeStamp: data.timeStamp, // 支付签名时间戳
        nonceStr: data.nonceStr, // 支付签名随机串
        package: data.packageStr, // 统一支付接口返回的 prepay_id 参数值
        signType: data.signType, // 签名算法，暂支持 MD5
        paySign: data.paySign, // 签名
        success(res) {
          console.log('支付成功');
          // 支付成功
          resolve(res);
          // that.getpaydOrder()
          console.log("支付结果", res.data);
        },
        fail(err) {
          // 支付失败
          reject(err);
          console.log('支付失败', err);
          // if (err.errMsg.includes("cancel")) {
          //   // 如果支付取消，跳转页面
          //   wx.switchTab({
          //     url: '/pages/order/index',
          //   });
          // }
        },
        complete() {
          // 支付结果处理完成
        },
      });
    })
  },

  // 消息的订阅与推送
  newSubscribe() {
    const that = this;
    console.log("消息的订阅");

    // 如果已经订阅过，则不再执行
    if (that.isSubscribed) {
      console.log("已经订阅，稍后再试");
      return;
    }

    // 弹出订阅消息询问框
    wx.requestSubscribeMessage({
      tmplIds: ['stIrrYYr3buMlS7abC3FmuXS8WB1Lvrv_uuOSk8q2x8'],
      success(res) {
        // 判断用户是否同意订阅
        if (res['stIrrYYr3buMlS7abC3FmuXS8WB1Lvrv_uuOSk8q2x8'] === 'accept') {
          console.log('用户已同意订阅消息');
        } else {
          console.log('用户拒绝订阅消息');
        }
        // 无论用户是否同意，都继续提交
        that.submit(); // 执行 submit 操作
        // 设定已订阅标志，并设置超时
        that.isSubscribed = true;
        setTimeout(() => {
          that.isSubscribed = false; // 超过时间后重置标志
        }, that.SUBSCRIBE_TIMEOUT);
      },
      fail(err) {
        console.error('订阅消息失败', err);
        // 订阅失败时也继续执行 submit
        that.submit();
      }
    });
  },

  toBack() {
    wx.navigateBack({
      delta: 1
    });
  },

})